import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {OneOperationComponent} from '../../../../widgets/one-operation/one-operation.component';
import {ActivatedRoute, Router} from '@angular/router';
import {TableUtil} from '../../../../util/table-util';
import {OneDialogService} from '../../../../widgets/one-dialog/one-dialog.service';
import {ResponseUtil} from '../../../../util/response-util';
import {PageSubject} from '../../../../util/page-subject';
import {Path} from '../../../../portal/admin/admin-breadcrumb/breadcrumb';
import {RecordService} from './record.service';
import {Type} from './Type';
import {MsgAPI} from '../../msg-constants';
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";
import {DataDictionaryService} from "../../../../services/dataDictionary.service";
import {Content} from "./content";


declare var $;
declare var moment;
declare var datepicker;

@Component({
  selector: 'app-record',
  templateUrl: './record.component.html',
  styleUrls: ['./record.component.css']
})
export class RecordComponent implements OnInit, AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  id: Array<string> = [];
  levels: Array<any> = [];
  totalNum: string = '0';
  handleNum: string = '0';
  noHandleNum: string = '0';
  // alarm: Map<String, any> = new Map();
  table;
  config;
  config2;
  content;

  types: Array<Type> = [{code: '1', name: '标准站'}, {code: '2', name: '微型站'}, {code: '3', name: '工业废气'}, {
    code: '4',
    name: '扬尘'
  }, {code: '5', name: '油烟'}, {code: '6', name: '喷漆房'}, {code: '7', name: '加油站'}, {code: '8', name: '工业废水'}, {
    code: '9',
    name: '水质断面'
  }, {
    code: '0',
    name: '因子报警'
  }];

  constructor(private router: Router,
              private route: ActivatedRoute,
              private tableUtil: TableUtil,
              private dialogService: OneDialogService,
              private recordService: RecordService,
              private dataDictionarysService: DataDictionaryService,
              private responseUtil: ResponseUtil,
              private pageSubject: PageSubject) {
  }


  ngOnInit() {
    this.initTime();
    this.pushPage();
    this.initLevels();
    this.initSummary();
    this.initContentObj();
  }

  //按钮点击触及事件
  proxy = {
    //报警处理
    "deal": () => this.deal(),
    //报警处理
    // "electronicDocument": () => this.exportElectronicDocument()
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 获取所有的元模板类型
   */
  initLevels() {
    this.dataDictionarysService.getChildDicByCode('BJDJ').subscribe(
      result => this.responseUtil.success(result, this.processResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  获取所有等级
   * @param json
   */
  private processResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.levels = result.data;
      this.loadAlarmRecord();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 获取汇总信息
   */
  initSummary() {
    this.recordService.getAlarmContentSummary().subscribe(
      result => this.responseUtil.success(result, this.processSummaryResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  处理汇总信息
   * @param json
   */
  private processSummaryResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.totalNum = result.data.totalNum;
      this.handleNum = result.data.handleNum;
      this.noHandleNum = result.data.noHandleNum;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("报警信息", "");
    this.pageSubject.pushPage("报警信息", "查询", path);
  }

  search2() {
    this.table.bootstrapTable('refresh');
  }

  private loadAlarmRecord() {
    this.table = this.tableUtil.load("one_table_record", {
      columns: [
        {checkbox: true, align: ''},
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "siteName", title: '站点名称', align: 'left', formatter: this.tableUtil.showToolTip},
        // {field: "siteCode", title: '站点编码', align: 'left'},
        {field: "SENDTIME", title: '报警时间', sortName: 'SENDTIME', sortable: true, align: 'left'},
        {field: "type", title: '报警类型', align: 'left', formatter: this.typeFormat},
        {field: "level", title: '报警等级', align: 'left', formatter: this.levelFormat},
        // {field: "sendMode", title: '报警方式', align: 'left', formatter: this.modeFormat},
        {field: "content", width: '32%', title: '报警消息', align: 'left', formatter: this.tableUtil.showToolTip},
        {field: "handler", title: '处理人', align: 'left'},
        {field: "handleStatus", title: '处理状态', align: 'left', formatter: this.handFormat},
        {field: "handleTime", title: '处理时间', align: 'left'},
        {field: "oper", title: '操作', align: 'left', formatter: () => {
          return '<a class="btn btn-default deal">警情处理</a>'
        },
        events:
          {'click .deal': this.dealClick}
        }
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 25, 50, 100],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: true,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_record",
      url: MsgAPI.alarmRecordPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.siteName = $("#siteName").val();
        //params.siteCode = $("#siteCode").val();
        params.startTime = $("#startTime").val();
        params.endTime = $("#endTime").val();
        params.type = $("#type").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.SENDTIME = value.sendTime || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      order: 'desc',
      sort: 'SENDTIME',
      undefinedText: '-',
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      //css
      classes: "table table-hover one-fixed-table",
      striped: true,//隔行变色
      mobileResponsive: true,//响应式
    });
  }


  private typeFormat(value, row, index) {
    if (value == '1') {
      return "标准站";
    }
    if (value == '2') {
      return "微型站";
    }
    if (value == '3') {
      return "工业废气";
    }
    if (value == '4') {
      return "扬尘";
    }
    if (value == '5') {
      return "油烟";
    }
    if (value == '6') {
      return "喷漆房";
    }
    if (value == '7') {
      return "加油站";
    }
    if (value == '8') {
      return "工业废水";
    }
    if (value == '9') {
      return "水质断面";
    }
    if (value == '0') {
      return "因子报警";
    }
  }

  modeFormat(value, row, index) {
    if (value == '1') {
      return "应用内";
    }
    if (value == '2') {
      return "短信";
    }
    if (value == '3') {
      return "邮件";
    }
  }

  levelFormat = (value) => {
    let result = "-";
    // console.log(value);
    // console.log(this.levels);
    this.levels.forEach((val) => {
      if (val.value == value) {
        result = "<span class='one-table-inline' style='background: " + val.describe + ";'>" + val.display + "</span>";
      }
    });
    return result;
  }

  handFormat = (value) => {
    if (value == '0') {
      return "未处理";
    }
    if (value == '1') {
      return "已处理";
    }

  }

  dealClick = (e, value, row) => {
    this.router.navigate(['deal', {id: row.id}], {relativeTo: this.route});
  }


  //初始化日期插件
  initTime() {
    let timeData = moment().format("YYYY-MM-DD HH:mm:ss");
    let startDate = moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss");

    this.config = {
      timePicker: true,
      timePickerIncrement: 1,
      singleDatePicker: true,
      timePicker24Hour: true,
      parentEl: $(".wrapper"),
      maxDate: moment().format("YYYY-MM-DD HH:mm:ss"),
      locale: {
        format: "YYYY-MM-DD HH:mm:ss",
        separator: " 至 ",
        applyLabel: '确定',
        cancelLabel: '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        firstDay: 1
      },
      // startDate: moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss"),
      startDate: moment().subtract(6, "month").format("YYYY-MM-DD HH:mm:ss"),
      endDate: moment().format("YYYY-MM-DD HH:mm:ss")
    };
    this.config2 = {
      timePicker: true,
      timePickerIncrement: 1,
      singleDatePicker: true,
      timePicker24Hour: true,
      parentEl: $(".wrapper"),
      // maxDate:timeData,
      locale: {
        format: "YYYY-MM-DD HH:mm:ss",
        separator: " 至 ",
        applyLabel: '确定',
        cancelLabel: '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        firstDay: 1
      },
      startDate: moment().format("YYYY-MM-DD HH:mm:ss"),
      endDate: moment().format("YYYY-MM-DD HH:mm:ss")
    };

    $("#startTime").daterangepicker(this.config);
    $("#endTime").daterangepicker(this.config2);
  }

  private deal() {
    let rows = this.table.bootstrapTable('getSelections');
    this.id = this.tableUtil.getCloumns(rows, "id");
    if (this.id.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['deal', {id: this.id[0]}], {relativeTo: this.route});
    }
  }

  initContentObj() {
    this.content = new Content;
  }

  /**
   * 导出电子报
   */
  exportExcelData() {
    this.content.startTime = $("#startTime").val();
    this.content.siteName = $('#siteName').val();
    this.content.endTime = $("#endTime").val();
    this.content.type = $("#type").val();
    this.recordService.exportExcelData(this.content);
  }

  processExcelResult = (result: any) => {
    let blob = new Blob([result], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
    let objectUrl = URL.createObjectURL(blob);
    var a = document.createElement('a');
    document.body.appendChild(a);
    a.setAttribute('style', 'display:none');
    a.setAttribute('href', objectUrl);
    a.setAttribute('target', '_blank');
    a.click();
    setTimeout(function () {
        URL.revokeObjectURL(objectUrl)
      }, 5000
    );
  }

  /**
   * 生成电子报告并发送到邮箱
   */
  sendExcelData() {
    this.content.startTime = $("#startTime").val();
    this.content.siteName = $('#siteName').val();
    this.content.endTime = $("#endTime").val();
    this.content.type = $("#type").val();
    this.recordService.sendExcelData(this.content).subscribe(
      result => this.responseUtil.success(result, this.processSendExcelResult),
      message => this.responseUtil.error(message)
    );
  }

  processSendExcelResult = (result: any) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalInfo(result.message);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

}
